<template>
	<modeBoxTemplate>
		<el-form :model="formData" :rules="rules" ref="ruleFormRef" label-position="top">
			<el-form-item prop="pathType" label="图片应用路径类型">
				<el-select v-model="formData.pathType" placeholder="选择路径类型">
					<el-option label="使用相对路径" value="relative" />
					<el-option label="使用绝对路径" value="absolute" />
				</el-select>
			</el-form-item>
			<el-form-item prop="saveMode" label="图片保存模式">
				<el-select v-model="formData.saveMode" placeholder="选择保存模式">
					<el-option label="统一保存" value="unifiedSave" />
					<el-option label="分别保存" value="separatelySave" />
				</el-select>
			</el-form-item>
			<el-form-item prop="unifiedSavePath" v-if="formData.saveMode === 'unifiedSave'" label="图片保存路径">
				<path-input
					v-model="formData.unifiedSavePath"
					type="dir"
					placeholder="图片保存路径"
					title="图片保存路径" />
			</el-form-item>
		</el-form>
		<el-button type="primary" @click="download" :disabled="workOngoing">开始下载</el-button>
	</modeBoxTemplate>
</template>

<script setup lang="ts">
import { API } from '@v/utils/API';
import { rootMixin } from '@v/mixin';
import { useRootStore } from '@v/store';
import { reactive, ref, watch } from 'vue';
import { ElMessageBox } from 'element-plus';
import { Mode1Data } from '@p/main-modeData';
import type { FormInstance } from 'element-plus';
import { useMode1Store } from '@v/store/mode/mode1';
import modeBoxTemplate from '../modeBoxTemplate.vue';
import { dirPathValidator } from '@v/utils/elementValidator';
import pathInput from '@v/components/form/path-input.vue';

const { workOngoing } = rootMixin();

const store = useRootStore();
const mode1Store = useMode1Store();

const ruleFormRef = ref<FormInstance>();

// 表单数据
const formData = reactive<Mode1Data>({
	pathType: 'relative', // absolute
	saveMode: 'unifiedSave', // unifiedSave / separatelySave
	unifiedSavePath: '',
	separatelySavePaths: [],
});

// 表单验证规则
const rules = reactive({
	unifiedSavePath: [
		{
			validator: dirPathValidator(),
			trigger: 'change',
		},
	],
});

// 下载函数
function download() {
	const obj: Mode1Data = JSON.parse(JSON.stringify(formData));
	obj.separatelySavePaths = mode1Store.separatelySavePaths;

	function send() {
		store.setWork(true, 'mode1');

		API.invoke('mode1', JSON.parse(JSON.stringify(obj)));
	}

	if (!ruleFormRef.value) return;

	ruleFormRef.value.validate((valid) => {
		if (!valid) return;

		if (obj.saveMode === 'separatelySave') {
			const length = obj.separatelySavePaths.reduce((s, item) => {
				s += item.children.length;

				return s;
			}, 0);

			if (mode1Store.length !== length) {
				return ElMessageBox.confirm('有图片未选择，未选择的图片将不会下载', '提示', {
					confirmButtonText: '不管，继续下载',
					cancelButtonText: '继续选择',
					type: 'warning',
				}).then(
					() => {
						send();
					},
					() => {}
				);
			}
		}

		send();
	});
}

watch(
	() => formData.saveMode,
	(newval) => {
		store.setDrawer_isShow(newval === 'separatelySave');
	}
);
</script>
